package com.chuiyan.topnews;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class ImgRecyclerAdapter extends RecyclerView.Adapter<ImgRecyclerAdapter.ViewHolder> {
    private ArrayList<JSONObject> jsonObjects;
    private final Context context;
    public ImgRecyclerAdapter(Context context, ArrayList<JSONObject> jsonObjects) {
        this.context = context;
        this.jsonObjects = jsonObjects;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemView = View.inflate(context,R.layout.item_img,null);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        JSONObject jsonObject = jsonObjects.get(i);
        try {
            viewHolder.title.setText(jsonObject.getString("title"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
            viewHolder.image.setImageResource(R.drawable.photo);
    }

    @Override
    public int getItemCount() {
        return jsonObjects.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        private TextView title;
        private ImageView image;
        public ViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            image = itemView.findViewById(R.id.image);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onItemClickListener!=null)
                    {
                        onItemClickListener.onItemClick(v,jsonObjects.get(getLayoutPosition()));
                    }
                }
            });
        }
    }
    public interface OnItemClickListener{
        public void onItemClick(View view,JSONObject jsonObject);
    }
    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}
